/* --------------------------------------------------------
 * Copyright (c) Express Scripts, Inc.  All rights reserved.
 * --------------------------------------------------------
 */
package com.aeky.common;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class ReflectionUtils.
 */
public final class ReflectionUtils {

    /** The logger. */
    private static final Logger LOG = LoggerFactory.getLogger(ReflectionUtils.class);

    /**
     * Instantiates a new reflection utils.
     */
    private ReflectionUtils() {
    }

    /**
     * Gets the field value.
     * 
     * @param object the object
     * @param fieldName the field name
     * 
     * @return the field value
     */
    public static Object getFieldValue(final Object object, final String fieldName) {
        Field field = getDeclaredField(object, fieldName);
        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }
        makeAccessible(field);
        Object result = null;
        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            LOG.error("getFieldValue", e);
        }
        return result;
    }

    /**
     * Sets the field value.
     * 
     * @param object the object
     * @param fieldName the field name
     * @param value the value
     */
    public static void setFieldValue(final Object object, final String fieldName, final Object value) {
        Field field = getDeclaredField(object, fieldName);
        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }
        makeAccessible(field);
        try {
            field.set(object, value);
        } catch (IllegalAccessException e) {
            LOG.error("setFieldValue", e);
        }
    }

    /**
     * Invoke method.
     * 
     * @param object the object
     * @param methodName the method name
     * @param parameterTypes the parameter types
     * @param parameters the parameters
     * 
     * @return the object
     * 
     * @throws InvocationTargetException the invocation target exception
     */
    public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes,
            final Object[] parameters) throws InvocationTargetException {
        Method method = getDeclaredMethod(object, methodName, parameterTypes);
        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
        }
        method.setAccessible(true);
        try {
            return method.invoke(object, parameters);
        } catch (IllegalAccessException e) {
            LOG.error("invokeMethod", e);
        }
        return null;
    }

    /**
     * Gets the declared field.
     * 
     * @param object the object
     * @param fieldName the field name
     * 
     * @return the declared field
     */
    protected static Field getDeclaredField(final Object object, final String fieldName) {
        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                LOG.error("getDeclaredField", e.getMessage());
            }
        }
        return null;
    }

    /**
     * Make accessible.
     * 
     * @param field the field
     */
    protected static void makeAccessible(final Field field) {
        if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
            field.setAccessible(true);
        }
    }

    /**
     * Gets the declared method.
     * 
     * @param object the object
     * @param methodName the method name
     * @param parameterTypes the parameter types
     * 
     * @return the declared method
     */
    protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {
        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                LOG.error("getDeclaredMethod", e);
            }
        }
        return null;
    }

    /**
     * Gets the super class genric type.
     * 
     * @param clazz the clazz
     * @param <T> Generic Class
     * 
     * @return the super class genric type
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * Gets the super class genric type.
     * 
     * @param clazz the clazz
     * @param index the index
     * 
     * @return the super class genric type
     */
    @SuppressWarnings("unchecked")
    public static Class getSuperClassGenricType(final Class clazz, final int index) {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            LOG.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
            return Object.class;
        }
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            LOG.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                    + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            LOG.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
            return Object.class;
        }
        return (Class) params[index];
    }

    /**
     * Fetch element property to list.
     * 
     * @param collection the collection
     * @param propertyName the property name
     * 
     * @return the list
     */
    @SuppressWarnings("unchecked")
    public static List fetchElementPropertyToList(final Collection collection, final String propertyName) {
        List list = new ArrayList();
        try {
            for (Object obj : collection) {
                list.add(PropertyUtils.getProperty(obj, propertyName));
            }
        } catch (Exception e) {
            convertToUncheckedException(e);
        }
        return list;
    }

    /**
     * Fetch element property to string.
     * 
     * @param collection the collection
     * @param propertyName the property name
     * @param separator the separator
     * 
     * @return the string
     */
    @SuppressWarnings("unchecked")
    public static String fetchElementPropertyToString(final Collection collection, final String propertyName,
            final String separator) {
        List list = fetchElementPropertyToList(collection, propertyName);
        return StringUtils.join(list, separator);
    }

    /**
     * Convert value.
     * 
     * @param value the value
     * @param toType the to type
     * 
     * @return the object
     */
    public static Object convertValue(Object value, Class<?> toType) {
        try {
            DateConverter dc = new DateConverter();
            dc.setUseLocaleFormat(true);
            dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
            ConvertUtils.register(dc, Date.class);
            return ConvertUtils.convert((String) value, toType);
        } catch (Exception e) {
            throw convertToUncheckedException(e);
        }
    }

    /**
     * Convert to unchecked exception.
     * 
     * @param e the e
     * 
     * @return the illegal argument exception
     */
    public static IllegalArgumentException convertToUncheckedException(Exception e) {
        if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
                || e instanceof NoSuchMethodException) {
            return new IllegalArgumentException("Refelction Exception.", e);
        } else {
            return new IllegalArgumentException(e);
        }
    }
}
